using DebounceThrottle;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CommunityToolkit.Mvvm.Messaging;
using AvaMaid.Messages;
using FanaticGene.AvaloniaMaid.Core;
using System.IO;

namespace AvaMaid.Views
{
    /// <summary>
    /// ControlThemeViewUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class ControlThemeViewUserControl : UserControl, IRecipient<LoadCodeEventArgs>
    {
        private DebounceDispatcher _dispatcher = new DebounceDispatcher(200);

        public ControlThemeViewUserControl()
        {
            InitializeComponent();
            WeakReferenceMessenger.Default.Register(this);
        }

        public void Receive(LoadCodeEventArgs message)
        {
            App.Current.Dispatcher.Invoke(() =>
            {
                PART_AvalonTextEditor.Text = message.Code;
            });
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var text = (sender as TextBox).Text;
            _dispatcher.Debounce(() =>
            {
                WeakReferenceMessenger.Default.Send(new SearchTextChangedEventArgs() { Sender = this, Text = text });
            });
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = sender as ListBox;
            if (listBox == null) return;
            var selected = listBox.SelectedItem as CodeUri;
            if (selected == null) return;
            PART_AvalonTextEditor.Text = File.ReadAllText(selected.FullPath);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetText(PART_AvalonTextEditor.SelectedText);
        }
    }
}
